package com.webtest.authoritydemo;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.webtest.mvctest2.dao.DaoBase;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/8/16 12:19
 */
public class UserDao extends DaoBase<User> {
    private Gson gson = new Gson();

    boolean exit(String username) {
        if (StringUtils.isEmpty(username)) {
            return false;
        }
        String sql = "SELECT count(name) FROM user WHERE name=?";
        long count = getForValue(sql, username);
        return count > 0;
    }

    User get(String username) {
        String sql = "SELECT authorities FROM user WHERE name=?";
        String json = getForValue(sql, username);
        List<Authority> authorities = new ArrayList<>();
        if (StringUtils.isNoneEmpty()) {
            authorities = gson.fromJson(json, new TypeToken<List<Authority>>() {
            }.getType());
        }
        return new User(username, authorities);
    }

    void update(String username, List<Authority> authorities) {
        String sql = "UPDATE user SET authorities=? WHERE name=?";
        if (CollectionUtils.isEmpty(authorities)) {
            authorities = new ArrayList<>();
        }
        String json = gson.toJson(authorities);
        update(sql, json, username);
    }
}
